package com.hzit.payweb.customer;

import com.hzit.paycommon.paycommonapi.resp.PayNotifyData;
import com.hzit.payweb.config.MqData;
import com.hzit.payweb.config.MyMessagePostProcessor;
import com.hzit.payweb.config.PayWebConfig;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hzit.payweb.config.RabbitMqConfig;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 支付通知的消费者
 */
@Component
public class PayNoticeCustomer {

    private Logger logger = LoggerFactory.getLogger(PayNoticeCustomer.class);

    @Autowired
    private PayWebConfig payWebConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitMqConfig.DEAD_LETTER_QUEUEA_NAME)
    public void receive(Message message, MqData mqData, Channel channel){
        logger.info("payNotifyData = " + mqData);

        //确认消费
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            //异步通知
            //restTemplate发送http post请求
            String rlt = restTemplate.postForObject(payWebConfig.getOrderNotifyUrl(),mqData.getPayNotifyData(),String.class);
            if("success".equals(rlt)){
                return;
            }

            //继续放入队列，5
//            MyMessagePostProcessor myMessagePostProcessor = new MyMessagePostProcessor(60000);

            MqData mqData1 = new MqData();
            mqData1.setId(String.valueOf(System.currentTimeMillis()));
            mqData1.setPayNotifyData(mqData.getPayNotifyData());
            rabbitTemplate.convertAndSend(RabbitMqConfig.BUSINESS_EXCHANGE_NAME,"",mqData1);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
